<?php

namespace Jtbk\Controller;
use Think\Page;
use Think\Controller;


/**
 * 集体备课控制器
 * @author水月居 <singliang@163.com>
 */
class IndexController extends Controller {
	public function _initialize()
    {
       header("Content-type: text/html; charset=utf-8");
       $uid=is_login();
       if($uid){
        $my['teacher']=query_user('nickname');
        $my['uid']=$uid;
        $this->assign(my,$my);               
          }else{
          $this->error('请先登录',U('/Home/User/login'),3);
        }	
    }

    /**
     * 集体备课首页
    */
    public function index(){
    	$subject=D('JxSubject');
    	$sublist=$subject->order(array('sort'=>'asc'))->where(array('satus'=>1))->field('id,subject,post_count,logo')->select();
	    $beikepost=D('JxBeikePost');
	    $order=array('subject'=>'desc','grade'=>'desc','update_time'=>'desc');
	    foreach($sublist as $key => $value){
	    	$value['postlist']=$beikepost
	    	->field('id,title,teacher,grade,update_time')
	    	->limit(6)->order($order)
	    	->where(array('subject_id'=>$value['id']))->select();
	    	$data[]=$value;
	    	
	    }
	    //dump($beikepost->getLastSql());// dump($sublist);
	    //dump($data);
      //最的上传列表
	    $newlist=$beikepost->field("id,grade,subject,teacher,title,update_time")->order(array('update_time'=>'desc'))->limit('0,6')->select();
      $this->assign('newlist',$newlist);
	    $this->assign('list', $data);
      $this->display();
    }
    /**添加集体备课信息*/
    public function add(){
       $sublist=D('JxSubject')->field('id,subject')->select();
       $this->assign(sublist,$sublist);
		 if(IS_POST){
        //检查表单是否为空
        $title=str_replace(' ','',I('post.title'));
            if(!$_POST['sid']){
                $this->error("请选择上传学科类别后再上传",Cookie('__forward__'),2);
                }
            if(!$title){
                $this->error("请检查课程标题是否填写完整",Cookie('__forward__'),2);
                }
        $beike=D('JxSubject');
        $sid=I('post.sid');
        $info=$beike->getSubjectInfo($sid);
        $subject= $info['subject'];
        $savepath=$info['savepath'];
        $content=I('post.content');
 
        $content=op_c($content);
        //dump($content);
        //exit;
       //将结果写入数据库
       $beikepost=D('JxBeikePost');
		    $data=array(
	             'subject_id' => $sid,
	             'grade'      => I('post.grade'),
	             'jx_time'    => I('post.jxtime'),
	             'content'    => $content,
		    	     'subject'    => $subject,
		    	     'savepath'   => $savepath,
		           "teacher"    => I('teacher'),                         
		           "title"      => $title,
	             's_key'      => $subject.','.I('grade').','.I('title').','.I('teacher').','.C('CUR_YEAR'),
		           "year"       => C('CUR_YEAR'),
		     ); 
			$beikepost->create($data);
			$id=$beikepost->add(); 
      if($id){        
        $this->success('备课资料登记成功，请继续上传对应文件资料！',U('Index/Upload/',array('postid'=>$id)),3);
        }	else{		             
  			$this->error('保存失败，请仔细检查是否填写完整！');
        }
      } 

       $this->display();
	}
/*编辑上传资料*/
  public function edit()
  {
  
  $id=I('get.id');
  $beikepost=D('JxBeikePost');
  $postinfo=$beikepost->field('s_key',true)->find($id);//排除指定项其他都选取
  //dump($postinfo);
  //dump($uid);
  if(!$postinfo){
      $this->error('参数错误');
     }else{
      $uid=is_login();
        if($uid!=$postinfo['uid']){
          $this->error('对不起，您不能修改别人上传的资料！');
        }
      $this->assign('info',$postinfo);
    }
  
  $file=D('JxBeikeFile');
    if($postinfo['files']){
      $postfiles=$file->field('id,cate,title')->where(array('post_id'=>$id))->select();
      $this->assign('postfiles',$postfiles);
      }
    if(IS_POST){
      $data=array(
      	'id'     =>I('post.id'),      	
      	'teacher'=>I('post.teacher'),
      	'grade'  =>I('post.grade'),
      	'subject'=>I('post.subject'),
      	'title'  =>I('post.title'),
        'content'=>I('post.content'),
      	);
      $beikepost->create($data);
      //dump($data);exit;
      $beikepost->save();
      $this->success('更新成功！');
    }
  $this->display();
  }
	/*上传文件类*/
	public function upload(){
        $postid=I('postid');
        $beikepost=D('JxBeikePost');
        $postinfo=$beikepost->field('content,s_key',true)->find($postid);//排除指定项其他都选取
        $this->assign('info',$postinfo);
        $file=D('JxBeikeFile');
        if($postinfo['files']){
        	$postfiles=$file->field('id,cate,title')->where(array('post_id'=>$postid))->select();
        	$this->assign('postfiles',$postfiles);
        }

       if(IS_POST){
       //post检测
       	if(!I('post.cate')){
          $this->error("请先选择上传类别后再上传",Cookie('__forward__'),3);
       	}
        if(!I('post.cate')){
          $this->error("请先选择上传类别后再上传",Cookie('__forward__'),3);
        }
       $postid=I('post.postid');
       $savepath=I('savepath').'/';
       $save= $postinfo['subject'].I('grade').$postinfo['title'].I('post.cate').I('teacher').date(ymd);
       $config = array(
            'maxSize'    =>   50*1024*1024, // 设置附件上传大小
            'rootPath'   =>    './Uploads/Beike/',
            'savePath'   =>     $savepath,
            'saveName'   =>    iconv('utf-8', 'gbk', $save),
            'exts'       =>    array('jpg', 'gif', 'png', 'zip', 'rar', 'doc', 'docx','ppt','swf','pdf'),
            'autoSub'    =>    true,
            'subName'    =>    C('CUR_YEAR'),
         );

          $upload = new \Think\Upload($config);// 实例化上传类 
          $info   =  $upload->upload();
			$file_ext = pathinfo($_FILES['upfile']['name'], PATHINFO_EXTENSION );
		    if(!$info) {// 上传错误提示错误信息
		        $this->error($upload->getError(),Cookie('__forward__'),3);
		      }else{
              // 上传成功保存表单数据				       
				      $url= $savepath.C('CUR_YEAR').'/'.$save.'.'.$file_ext;    
				    	$data=array(
				         'post_id'   => $postid,
				         'cate'      => I('post.cate'),
						 "file_url"  => $url,
		                 'subject_id' => $postinfo['subject_id'],
		                 'grade'     => I('post.grade'),
		                 'subject'   => $postinfo['subject'],
				         "teacher"   => I('teacher'),                         
				         "file_name" => $_FILES['upfile']['name'],
				         'url'       => $url,
                         'file_ext'  => $file_ext,
				         "title"     => $postinfo['title'],
                         "year"      => C('CUR_YEAR'),
				         );
				 $file->create($data);
		         if($file->add()){ 
				         $beikepost->where($postid)->setInc('files');   
				         $this->success('上传成功！');		         	
				        }else{
				         $this->success('保存失败！');
		            }
		       }
        }
       $this->display();
	}
	/**@水月居
	*我的上传*
	**/
	public function myupload($uid=0)
	{
	  	$uid=is_login();
	  	$map['uid'] = $uid;
	    $list=D('JxBeikePost')->where($map)->select();
	    $this->assign('list',$list);
	  $this->display();
	 }
   /**@todo
	*显示文档详情*
	**/
  public function detail($id=0) {
    $post_id=I('get.id'); 
    $beikepost=D('JxBeikePost');
    $post=$beikepost->find($post_id);
    $upfiles=D('JxBeikeFile')->field('id,post_id,cate')->where(array('post_id'=>$post_id))->select();
    $this->assign('files',$upfiles);
    $this->assign('alist',$post);
    $this->display();
  }
   /**@todo
  *下载附件*
  **/
   public function download(){
    $id=I('fid');
    $afile=D('JxBeikeFile')->find($id);

    //判断文件是否存在
    $file_path = './Uploads/Beike/'.$afile['file_url'];
    
    $file_path = iconv('utf-8', 'gb2312', $file_path); //对可能出现的中文名称进行转码
    if (!file_exists($file_path)) {
      $this->error('文件不存在！');
    }
    $file_name = str_replace(' ','',$afile['file_name']);  //获取文件名称 basename()
    $file_size = filesize($file_path); //获取文件大小
    $fp = fopen($file_path, 'r'); //以只读的方式打开文件
    header("Content-type: application/octet-stream");
    header("Accept-Ranges: bytes");
    header("Accept-Length: {$file_size}");
            if (preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) { //for IE
                 header('Content-Disposition: attachment; filename="' . rawurlencode($file_name) . '"');
             } else {
                 header('Content-Disposition: attachment; filename="' . $file_name . '"');
             }
    //header("Content-Disposition: attachment;filename={$file_name}");
    $buffer = 1024;
    $file_count = 0;
    //判断文件是否结束
    while (!feof($fp) && ($file_size-$file_count>0)) {
    $file_data = fread($fp, $buffer);
    $file_count += $buffer;
    echo $file_data;
    }
    fclose($fp); //关闭文件
    }
    /**
    * 删除文件
    * @param string $filename
    */
   public function delFile($fileid) {
    if (file_exists($filename)) unlink($filename);
    }
     
	/**todo
	*集体备课查询
	*/
   public function search(){
    
    $sublist=D('JxSubject')->order(array('sort'=>'asc'))->where(array('satus'=>1))->field('id,subject')->select();
   	/**查询字段条件拼组**/ 
    $map['status']=1;
    $search=I('keywords');
    $grade =I('post.grade');
    $subject=I('post.subject');
    if(!empty($search)){
      $map['s_key'] = array('like','%'.$search.'%');
    }else{
      unset($map['s_key']);
    }
   if('所有年级'==$grade||empty($grade)){
    unset($map['grade']);
   }else{
    $map['grade']=I('grade');
   }
   if('所有学科'==$subject||empty($subject)){
    unset($map['subject']);
   }else{
    $map['subject']=I('subject');
   }
  
  
   	//like模糊查询
   	$postsearch=D('JxBeikePost')->field('content,status,last_reply_time,s_key',true)->order('update_time desc')
   	            ->where($map)->limit(20)->select();
    //dump($map);
    //dump($sublist);
    //dump($postsearch);
     $this->assign('list',$postsearch);
     $this->assign('subjectlist',$sublist);
     $this->display();
   }
  /*显示科目集体备课信息 */
    public function listsub($sid=0){
      $sid=I('get.sid'); 
      if(!$sid==0) {
        $subject=D('JxBeike')->find($sid);//获取科目信息
    	$beikepost=D('JxBeikePost');
	    $order=array('grade'=>'desc','update_time'=>'desc');	   
	    $data=$beikepost->field('id,title,teacher,subject,grade,update_time')
	    ->limit(10)->order($order)
	    ->where(array('subject_id'=>$sid))->select();
	    }else{
	    	 $this->error('课程号错误',Cookie('__forward__'),3);
	    }	
      $this->assign('subject', $subject);
      $this->assign('list', $data);
  $this->display();
  }


}